import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  Tabs,
  Table,
  Modal,
  Form,
  Input,
  Select,
  message,
  Statistic,
  Tag,
  Avatar,
  Tooltip,
  Descriptions,
  Alert,
  Typography,
  Divider,
  List,
  Badge,
  Progress,
  Timeline
} from 'antd';
import {
  ApiOutlined,
  KeyOutlined,
  DownloadOutlined,
  FileTextOutlined,
  CodeOutlined,
  BarChartOutlined,
  SettingOutlined,
  PlusOutlined,
  CopyOutlined,
  EyeOutlined,
  DeleteOutlined,
  ReloadOutlined,
  BugOutlined,
  RocketOutlined,
  BookOutlined,
  CloudDownloadOutlined
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

interface ApiApplication {
  id: string;
  name: string;
  description: string;
  status: 'active' | 'inactive' | 'suspended';
  apiKeys: ApiKey[];
  allowedIps: string[];
  createdAt: string;
  lastUsed?: string;
  totalCalls: number;
  todayCalls: number;
  errorRate: number;
}

interface ApiKey {
  id: string;
  appId: string;
  accessKey: string;
  secretKey: string;
  permissions: string[];
  expiresAt?: string;
  createdAt: string;
  lastUsed?: string;
  callCount: number;
  status: 'active' | 'expired' | 'revoked';
}

interface ApiCall {
  id: string;
  appId: string;
  appName: string;
  endpoint: string;
  method: string;
  statusCode: number;
  responseTime: number;
  timestamp: string;
  ip: string;
  userAgent: string;
}

const { TabPane } = Tabs;
const { Text, Title, Paragraph } = Typography;
const { Option } = Select;

export default function DeveloperCenter() {
  const [applications, setApplications] = useState<ApiApplication[]>([]);
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const [apiCalls, setApiCalls] = useState<ApiCall[]>([]);
  const [loading, setLoading] = useState(false);
  const [appModalVisible, setAppModalVisible] = useState(false);
  const [keyModalVisible, setKeyModalVisible] = useState(false);
  const [selectedApp, setSelectedApp] = useState<ApiApplication | null>(null);
  const [activeTab, setActiveTab] = useState('overview');
  const [form] = Form.useForm();
  const [keyForm] = Form.useForm();

  // 模拟数据
  const mockApplications: ApiApplication[] = [
    {
      id: '1',
      name: '移动端应用',
      description: '移动端APP的API调用',
      status: 'active',
      apiKeys: [],
      allowedIps: ['*'],
      createdAt: '2024-01-15T10:00:00Z',
      lastUsed: '2024-01-25T14:30:00Z',
      totalCalls: 15420,
      todayCalls: 234,
      errorRate: 0.02
    },
    {
      id: '2',
      name: 'Web前端',
      description: 'Web前端页面的API调用',
      status: 'active',
      apiKeys: [],
      allowedIps: ['192.168.1.0/24'],
      createdAt: '2024-01-10T09:00:00Z',
      lastUsed: '2024-01-25T16:45:00Z',
      totalCalls: 8765,
      todayCalls: 156,
      errorRate: 0.01
    }
  ];

  const mockApiKeys: ApiKey[] = [
    {
      id: '1',
      appId: '1',
      accessKey: 'ak_1234567890abcdef',
      secretKey: 'sk_abcdef1234567890',
      permissions: ['user:read', 'workflow:execute'],
      expiresAt: '2024-12-31T23:59:59Z',
      createdAt: '2024-01-15T10:00:00Z',
      lastUsed: '2024-01-25T14:30:00Z',
      callCount: 15420,
      status: 'active'
    },
    {
      id: '2',
      appId: '2',
      accessKey: 'ak_fedcba0987654321',
      secretKey: 'sk_0987654321fedcba',
      permissions: ['user:read', 'form:submit'],
      createdAt: '2024-01-10T09:00:00Z',
      lastUsed: '2024-01-25T16:45:00Z',
      callCount: 8765,
      status: 'active'
    }
  ];

  const mockApiCalls: ApiCall[] = [
    {
      id: '1',
      appId: '1',
      appName: '移动端应用',
      endpoint: '/api/v1/users/profile',
      method: 'GET',
      statusCode: 200,
      responseTime: 125,
      timestamp: '2024-01-25T16:45:30Z',
      ip: '192.168.1.100',
      userAgent: 'UniflowApp/1.0.0'
    },
    {
      id: '2',
      appId: '2',
      appName: 'Web前端',
      endpoint: '/api/v1/workflows/list',
      method: 'GET',
      statusCode: 200,
      responseTime: 89,
      timestamp: '2024-01-25T16:44:15Z',
      ip: '192.168.1.50',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
    }
  ];

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setApplications(mockApplications);
      setApiKeys(mockApiKeys);
      setApiCalls(mockApiCalls);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateApp = async (values: any) => {
    try {
      const newApp: ApiApplication = {
        id: Date.now().toString(),
        ...values,
        status: 'active',
        apiKeys: [],
        allowedIps: values.allowedIps ? values.allowedIps.split(',').map((ip: string) => ip.trim()) : ['*'],
        createdAt: new Date().toISOString(),
        totalCalls: 0,
        todayCalls: 0,
        errorRate: 0
      };
      setApplications([...applications, newApp]);
      setAppModalVisible(false);
      form.resetFields();
      message.success('应用创建成功');
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleCreateKey = async (values: any) => {
    try {
      const newKey: ApiKey = {
        id: Date.now().toString(),
        appId: values.appId,
        accessKey: `ak_${Math.random().toString(36).substr(2, 16)}`,
        secretKey: `sk_${Math.random().toString(36).substr(2, 16)}`,
        permissions: values.permissions || [],
        expiresAt: values.expiresAt,
        createdAt: new Date().toISOString(),
        callCount: 0,
        status: 'active'
      };
      setApiKeys([...apiKeys, newKey]);
      setKeyModalVisible(false);
      keyForm.resetFields();
      message.success('API密钥创建成功');
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleDeleteApp = async (id: string) => {
    try {
      setApplications(applications.filter(app => app.id !== id));
      setApiKeys(apiKeys.filter(key => key.appId !== id));
      message.success('应用删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleRevokeKey = async (id: string) => {
    try {
      setApiKeys(apiKeys.map(key => 
        key.id === id ? { ...key, status: 'revoked' as const } : key
      ));
      message.success('API密钥已撤销');
    } catch (error) {
      message.error('撤销失败');
    }
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      active: 'green',
      inactive: 'orange',
      suspended: 'red',
      expired: 'red',
      revoked: 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      active: '活跃',
      inactive: '非活跃',
      suspended: '已暂停',
      expired: '已过期',
      revoked: '已撤销'
    };
    return texts[status] || status;
  };

  const appColumns: ColumnsType<ApiApplication> = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.description}</div>
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '今日调用',
      dataIndex: 'todayCalls',
      key: 'todayCalls',
      render: (count) => <Badge count={count} showZero />
    },
    {
      title: '总调用数',
      dataIndex: 'totalCalls',
      key: 'totalCalls',
      render: (count) => count.toLocaleString()
    },
    {
      title: '错误率',
      dataIndex: 'errorRate',
      key: 'errorRate',
      render: (rate) => (
        <span style={{ color: rate > 0.05 ? 'red' : 'green' }}>
          {(rate * 100).toFixed(2)}%
        </span>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => setSelectedApp(record)}
            />
          </Tooltip>
          <Tooltip title="管理密钥">
            <Button
              type="text"
              icon={<KeyOutlined />}
              onClick={() => {
                setSelectedApp(record);
                setActiveTab('keys');
              }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="text"
              icon={<DeleteOutlined />}
              danger
              onClick={() => {
                Modal.confirm({
                  title: '确定删除这个应用吗？',
                  content: '删除后将无法恢复，相关的API密钥也会被删除。',
                  onOk: () => handleDeleteApp(record.id)
                });
              }}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  const keyColumns: ColumnsType<ApiKey> = [
    {
      title: 'Access Key',
      dataIndex: 'accessKey',
      key: 'accessKey',
      render: (key) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Text code>{key}</Text>
          <Button
            type="text"
            size="small"
            icon={<CopyOutlined />}
            onClick={() => {
              navigator.clipboard.writeText(key);
              message.success('已复制到剪贴板');
            }}
          />
        </div>
      )
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions) => (
        <div>
          {permissions.slice(0, 2).map((perm: string) => (
            <Tag key={perm}>{perm}</Tag>
          ))}
          {permissions.length > 2 && (
            <Tag>+{permissions.length - 2}</Tag>
          )}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '调用次数',
      dataIndex: 'callCount',
      key: 'callCount',
      render: (count) => count.toLocaleString()
    },
    {
      title: '过期时间',
      dataIndex: 'expiresAt',
      key: 'expiresAt',
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD') : '永不过期'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            size="small"
            onClick={() => {
              Modal.info({
                title: 'API密钥详情',
                width: 600,
                content: (
                  <div>
                    <Descriptions column={1} size="small">
                      <Descriptions.Item label="Access Key">
                        <Text code>{record.accessKey}</Text>
                      </Descriptions.Item>
                      <Descriptions.Item label="Secret Key">
                        <Text code>{record.secretKey}</Text>
                      </Descriptions.Item>
                      <Descriptions.Item label="权限">
                        {record.permissions.map(perm => (
                          <Tag key={perm}>{perm}</Tag>
                        ))}
                      </Descriptions.Item>
                      <Descriptions.Item label="创建时间">
                        {dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                      </Descriptions.Item>
                      <Descriptions.Item label="最后使用">
                        {record.lastUsed ? dayjs(record.lastUsed).format('YYYY-MM-DD HH:mm:ss') : '从未使用'}
                      </Descriptions.Item>
                    </Descriptions>
                  </div>
                )
              });
            }}
          >
            查看
          </Button>
          {record.status === 'active' && (
            <Button
              type="text"
              size="small"
              danger
              onClick={() => {
                Modal.confirm({
                  title: '确定撤销这个API密钥吗？',
                  content: '撤销后将无法恢复，使用此密钥的应用将无法访问API。',
                  onOk: () => handleRevokeKey(record.id)
                });
              }}
            >
              撤销
            </Button>
          )}
        </Space>
      )
    }
  ];

  const callColumns: ColumnsType<ApiCall> = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (date) => dayjs(date).format('HH:mm:ss')
    },
    {
      title: '应用',
      dataIndex: 'appName',
      key: 'appName'
    },
    {
      title: '接口',
      dataIndex: 'endpoint',
      key: 'endpoint',
      render: (endpoint, record) => (
        <div>
          <Tag color="blue">{record.method}</Tag>
          <Text code>{endpoint}</Text>
        </div>
      )
    },
    {
      title: '状态码',
      dataIndex: 'statusCode',
      key: 'statusCode',
      render: (code) => (
        <Tag color={code >= 200 && code < 300 ? 'green' : 'red'}>
          {code}
        </Tag>
      )
    },
    {
      title: '响应时间',
      dataIndex: 'responseTime',
      key: 'responseTime',
      render: (time) => `${time}ms`
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip'
    }
  ];

  const sdkList = [
    {
      name: 'JavaScript SDK',
      description: '适用于Web前端和Node.js环境',
      version: 'v1.2.0',
      size: '45KB',
      downloads: 1234
    },
    {
      name: 'Python SDK',
      description: '适用于Python 3.6+环境',
      version: 'v1.1.0',
      size: '78KB',
      downloads: 856
    },
    {
      name: 'Java SDK',
      description: '适用于Java 8+环境',
      version: 'v1.0.0',
      size: '156KB',
      downloads: 567
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>开发者中心</Title>
        <Paragraph>
          欢迎使用统一工作流平台开发者中心。这里提供完整的API文档、SDK下载、应用管理和调用统计功能。
        </Paragraph>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        {/* 概览 */}
        <TabPane tab={<span><BarChartOutlined />概览</span>} key="overview">
          <Row gutter={[16, 16]}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="API应用数"
                  value={applications.length}
                  prefix={<ApiOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="活跃密钥数"
                  value={apiKeys.filter(k => k.status === 'active').length}
                  prefix={<KeyOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="今日调用数"
                  value={applications.reduce((sum, app) => sum + app.todayCalls, 0)}
                  prefix={<RocketOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="总调用数"
                  value={applications.reduce((sum, app) => sum + app.totalCalls, 0)}
                  prefix={<BarChartOutlined />}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginTop: 16 }}>
            <Col span={12}>
              <Card title="API调用趋势" size="small">
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                  调用趋势图表（待集成图表库）
                </div>
              </Card>
            </Col>
            <Col span={12}>
              <Card title="错误率统计" size="small">
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                  错误率统计图表（待集成图表库）
                </div>
              </Card>
            </Col>
          </Row>

          <Card title="快速开始" style={{ marginTop: 16 }}>
            <Timeline>
              <Timeline.Item>
                <strong>1. 创建API应用</strong>
                <div>在应用管理页面创建您的第一个API应用</div>
              </Timeline.Item>
              <Timeline.Item>
                <strong>2. 生成API密钥</strong>
                <div>为您的应用生成访问密钥，配置相应权限</div>
              </Timeline.Item>
              <Timeline.Item>
                <strong>3. 下载SDK</strong>
                <div>选择适合您开发语言的SDK，快速集成API</div>
              </Timeline.Item>
              <Timeline.Item>
                <strong>4. 开始调用</strong>
                <div>参考API文档，开始调用我们的服务</div>
              </Timeline.Item>
            </Timeline>
          </Card>
        </TabPane>

        {/* 应用管理 */}
        <TabPane tab={<span><ApiOutlined />应用管理</span>} key="applications">
          <div style={{ marginBottom: 16 }}>
            <Space>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => setAppModalVisible(true)}>
                创建应用
              </Button>
              <Button icon={<ReloadOutlined />} onClick={loadData}>
                刷新
              </Button>
            </Space>
          </div>
          
          <Table
            columns={appColumns}
            dataSource={applications}
            rowKey="id"
            loading={loading}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </TabPane>

        {/* API密钥 */}
        <TabPane tab={<span><KeyOutlined />API密钥</span>} key="keys">
          <div style={{ marginBottom: 16 }}>
            <Space>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => setKeyModalVisible(true)}>
                生成密钥
              </Button>
              <Button icon={<ReloadOutlined />} onClick={loadData}>
                刷新
              </Button>
            </Space>
          </div>
          
          <Alert
            message="安全提醒"
            description="请妥善保管您的API密钥，不要在客户端代码中暴露Secret Key。建议定期轮换密钥以确保安全。"
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
          
          <Table
            columns={keyColumns}
            dataSource={apiKeys}
            rowKey="id"
            loading={loading}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </TabPane>

        {/* API文档 */}
        <TabPane tab={<span><FileTextOutlined />API文档</span>} key="docs">
          <Card>
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <ApiOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
              <Title level={3}>API文档</Title>
              <Paragraph>
                完整的API接口文档，包含所有接口的详细说明、参数定义和示例代码。
              </Paragraph>
              <Space size="large">
                <Button type="primary" size="large" icon={<FileTextOutlined />}>
                  查看在线文档
                </Button>
                <Button size="large" icon={<DownloadOutlined />}>
                  下载PDF文档
                </Button>
              </Space>
            </div>
            
            <Divider>API接口概览</Divider>
            <Row gutter={16}>
              <Col span={8}>
                <Card size="small">
                  <Statistic title="用户管理" value={12} suffix="个接口" />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic title="工作流" value={18} suffix="个接口" />
                </Card>
              </Col>
              <Col span={8}>
                <Card size="small">
                  <Statistic title="表单管理" value={15} suffix="个接口" />
                </Card>
              </Col>
            </Row>
          </Card>
        </TabPane>

        {/* SDK下载 */}
        <TabPane tab={<span><CloudDownloadOutlined />SDK下载</span>} key="sdk">
          <Row gutter={16}>
            {sdkList.map((sdk, index) => (
              <Col span={8} key={index}>
                <Card
                  title={sdk.name}
                  extra={<Tag color="blue">{sdk.version}</Tag>}
                  actions={[
                    <Button type="primary" icon={<DownloadOutlined />}>
                      下载
                    </Button>,
                    <Button icon={<BookOutlined />}>
                      文档
                    </Button>
                  ]}
                >
                  <Paragraph>{sdk.description}</Paragraph>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#666' }}>
                    <span>大小: {sdk.size}</span>
                    <span>下载: {sdk.downloads}</span>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
          
          <Card title="安装说明" style={{ marginTop: 16 }}>
            <Tabs>
              <TabPane tab="JavaScript" key="js">
                <Text code>npm install uniflow-sdk</Text>
                <Divider />
                <pre style={{ background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
{`import { UniflowClient } from 'uniflow-sdk';

const client = new UniflowClient({
  accessKey: 'your-access-key',
  secretKey: 'your-secret-key',
  baseURL: 'https://api.uniflow.com'
});

// 获取用户信息
const user = await client.users.getProfile();
console.log(user);`}
                </pre>
              </TabPane>
              <TabPane tab="Python" key="python">
                <Text code>pip install uniflow-sdk</Text>
                <Divider />
                <pre style={{ background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
{`from uniflow import UniflowClient

client = UniflowClient(
    access_key='your-access-key',
    secret_key='your-secret-key',
    base_url='https://api.uniflow.com'
)

# 获取用户信息
user = client.users.get_profile()
print(user)`}
                </pre>
              </TabPane>
              <TabPane tab="Java" key="java">
                <Text code>implementation 'com.uniflow:uniflow-sdk:1.0.0'</Text>
                <Divider />
                <pre style={{ background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
{`import com.uniflow.UniflowClient;
import com.uniflow.model.User;

UniflowClient client = new UniflowClient.Builder()
    .accessKey("your-access-key")
    .secretKey("your-secret-key")
    .baseUrl("https://api.uniflow.com")
    .build();

// 获取用户信息
User user = client.users().getProfile();
System.out.println(user);`}
                </pre>
              </TabPane>
            </Tabs>
          </Card>
        </TabPane>

        {/* 调用日志 */}
        <TabPane tab={<span><BugOutlined />调用日志</span>} key="logs">
          <div style={{ marginBottom: 16 }}>
            <Space>
              <Select placeholder="选择应用" style={{ width: 200 }}>
                <Option value="">全部应用</Option>
                {applications.map(app => (
                  <Option key={app.id} value={app.id}>{app.name}</Option>
                ))}
              </Select>
              <Select placeholder="状态码" style={{ width: 120 }}>
                <Option value="">全部</Option>
                <Option value="200">200</Option>
                <Option value="400">400</Option>
                <Option value="500">500</Option>
              </Select>
              <Button icon={<ReloadOutlined />} onClick={loadData}>
                刷新
              </Button>
            </Space>
          </div>
          
          <Table
            columns={callColumns}
            dataSource={apiCalls}
            rowKey="id"
            loading={loading}
            size="small"
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </TabPane>
      </Tabs>

      {/* 创建应用模态框 */}
      <Modal
        title="创建API应用"
        open={appModalVisible}
        onCancel={() => setAppModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateApp}
        >
          <Form.Item
            label="应用名称"
            name="name"
            rules={[{ required: true, message: '请输入应用名称' }]}
          >
            <Input placeholder="请输入应用名称" />
          </Form.Item>
          
          <Form.Item
            label="应用描述"
            name="description"
            rules={[{ required: true, message: '请输入应用描述' }]}
          >
            <Input.TextArea rows={3} placeholder="请输入应用描述" />
          </Form.Item>
          
          <Form.Item
            label="IP白名单"
            name="allowedIps"
            help="多个IP用逗号分隔，* 表示允许所有IP"
          >
            <Input placeholder="192.168.1.0/24, 10.0.0.1, *" />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建
              </Button>
              <Button onClick={() => setAppModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 生成密钥模态框 */}
      <Modal
        title="生成API密钥"
        open={keyModalVisible}
        onCancel={() => setKeyModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={keyForm}
          layout="vertical"
          onFinish={handleCreateKey}
        >
          <Form.Item
            label="选择应用"
            name="appId"
            rules={[{ required: true, message: '请选择应用' }]}
          >
            <Select placeholder="请选择应用">
              {applications.map(app => (
                <Option key={app.id} value={app.id}>{app.name}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            label="权限"
            name="permissions"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <Select mode="multiple" placeholder="请选择权限">
              <Option value="user:read">用户读取</Option>
              <Option value="user:write">用户写入</Option>
              <Option value="workflow:read">工作流读取</Option>
              <Option value="workflow:execute">工作流执行</Option>
              <Option value="form:read">表单读取</Option>
              <Option value="form:submit">表单提交</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            label="过期时间"
            name="expiresAt"
            help="留空表示永不过期"
          >
            <Input type="datetime-local" />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                生成
              </Button>
              <Button onClick={() => setKeyModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}